package cn.collin.commons.web.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.taglibs.standard.tag.el.core.ExpressionUtil;
import org.hibernate.Session;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import cn.collin.commons.web.filter.OpenSessionInViewHibernateFilter;

/**
 * Return the persistent instance of the given entity class with the given
 * identifier
 * 
 * http://collincode.googlecode.com
 * 
 * @author collin.code@gmail.com
 * 
 */

public class HLoadTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	String var;

	Long id;

	String clazz;

	String id_el;

	public void setClazz(String clazz) {
		this.clazz = clazz;
	}

	@Override
	public void setId(String id) {
		this.id_el = id;
	}

	public void setVar(String var) {
		this.var = var;
	}

	@Override
	public int doStartTag() throws JspException {
		id = (Long) ExpressionUtil.evalNotNull("hload", "id", id_el,
				Long.class, this, pageContext);
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		Session session = (Session) TransactionSynchronizationManager
				.getResource(OpenSessionInViewHibernateFilter.SESSION_NAME);
		Object obj = session.load(clazz, id);
		pageContext.setAttribute(var, obj, PageContext.PAGE_SCOPE);
		return EVAL_PAGE;
	}

}
